import ReactDOM from 'react-dom/client';
import libs from './libs';

const App = () => {
    let cards = [];
    const localCards = localStorage.getItem('cards');
    if (localCards) {
        cards = JSON.parse(localCards);
    }

    const componentLibs = new Map();
    libs.map((module) => {
        componentLibs.set(module.props!.name, module.component)
    })

    const renderCard = (list) => {
        return list.map(data => {
            const View = componentLibs.get(data.name)
            const positionStyle = data.type === 'fixed' ? { position: 'absolute', left: data.left + 'px', top: data.top + 'px' } : {};
            const viewProps =Object.keys(data.data.props).reduce((pv, cv) => {
                pv[cv] = data.data.props[cv].initialValue;
                return pv;
            }, {})
    
            if (data.width) viewProps.width = data.width;
            if (data.height) viewProps.height = data.height;
            let renderDom;
            if(data.childrens?.length > 0) {
                renderDom = <View {...viewProps}>{renderCard(data.childrens)}</View>
            } else {
                renderDom = <View {...viewProps}></View>
            }

            return <div style={{ position: 'relative', width: viewProps.width || data.width, height: viewProps.height || data.height, ...positionStyle, }}>
                {View ? renderDom : data.name}
            </div>
        })
    }

    return <>{ renderCard(cards) }
    </>
}

ReactDOM.createRoot(document.getElementById('root')!).render(
    <App />
)